package
{
	import flash.events.EventDispatcher;
	
	import mx.controls.Alert;
	import mx.utils.ObjectUtil;
	
	
	public dynamic class Executer extends EventDispatcher
	{
		public var lastEvent:* = null;
		public var lastToken:* = null;
		public var index:int = 0;
		public var vars:Array = new Array();
		public var functions:Array = new Array();
		public static var executer:Executer = null;
		private var onComplete:Function;
		
		public function Executer()
		{
			super();
		}
		
		public function executeFunctionArray(functionArray:Array):void
		{
			index++;
			functions[index] = functionArray;
			nextCommand();
		}
		
		public function execute( ... args ):void
		{
			index++;
			functions[index] = args;
			nextCommand();
		}

		
		private function nextCommand () : void
		{
			if(functions[index])
			{
				if (functions[index].length > 0)
				{
					var currentFunction:Function = functions[index].shift();
					setOnComplete( nextCommand );
					currentFunction();
				}
				else
				{
					//if(onComplete != null) onComplete();
					onComplete	=	null;
					index--;
					if(index>0)
					{
						nextCommand();
					}
				}
			}
		}
		
		public function breaks():void
		{
			functions[index] = new Array();
			index--;
			if(index>0)
				nextCommand();
		}
		
		public function returns(object:*=null):void
		{
			lastEvent = object;
			breaks();
		}
		
		public function continues(object:*=null):void
		{
			if(object!=null)
				lastEvent = object;
			nextCommand();
		}
		
		public function onEvent(event:*,token:*=null):void
		{
			lastEvent = event;
			lastToken = token;
			continues();
		}
		
		public function setOnComplete ( value:Function ) : void 
		{ 
			onComplete = value; 
		}

		public static function getInstance():Executer
		{
			if(Executer.executer == null)
			{
				Executer.executer = new Executer();
			}
			return Executer.executer;		
		}

	}
}